package com.sign2024.sign2024project.signBase.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sign2024.sign2024core.common.constants.CommonConstants;
import com.sign2024.sign2024core.common.exeception.CommonException;
import com.sign2024.sign2024project.signBase.entry.BaseDisclose;
import com.sign2024.sign2024project.signBase.mapper.BaseDiscloseMapper;
import com.sign2024.sign2024project.signBase.param.BaseDiscloseParam;
import com.sign2024.sign2024project.signBase.service.BaseDiscloseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yujie
 * @data 2024/11/27 9:11
 */
@Service
public class BaseDiscloseServiceImpl implements BaseDiscloseService {

    @Resource
    private BaseDiscloseMapper baseDiscloseMapper;

    @Override
    public void insertBaseDisclose(BaseDisclose baseDisclose) {
        if (baseDisclose.getBaseName() == null) {
            throw new CommonException(CommonConstants.ERROR, "基地名称不可为空");
        }

        BaseDisclose disclose = baseDiscloseMapper.selectBaseByName(baseDisclose.getBaseName());
        if (disclose != null) {
            throw new CommonException(CommonConstants.ERROR, "该基地已存在，请核对信息");
        }

        baseDiscloseMapper.insertBaseDisclose(baseDisclose);
    }

    @Override
    public void updateBaseDisclose(BaseDisclose baseDisclose) {
        if (baseDisclose.getBaseName() == null) {
            throw new CommonException(CommonConstants.ERROR, "基地名称不可为空");
        }

        BaseDisclose disclose = baseDiscloseMapper.selectBaseByName(baseDisclose.getBaseName());
        if (disclose != null) {
            if (disclose.getId().equals(baseDisclose.getId())) {
                baseDiscloseMapper.updateBaseDisclose(baseDisclose);
            } else {
                throw new CommonException(CommonConstants.ERROR, "该基地已存在，请核对信息");
            }
        } else {
            baseDiscloseMapper.updateBaseDisclose(baseDisclose);
        }
    }

    @Override
    public Page<BaseDisclose> pageBaseDisclose(BaseDiscloseParam param) {
        Integer offset = (param.getPageNum() - 1) * param.getPageSize();
        param.setOffset(offset);

        // 分页查询
        Page<BaseDisclose> page = new Page<>(param.getPageNum(), param.getPageSize());
        List<BaseDisclose> list = baseDiscloseMapper.selectBaseDiscloseByPage(param);

        // 页码
        page.setCurrent(param.getPageNum());
        page.setSize(param.getPageSize());

        // 总记录数
        Long aLong = baseDiscloseMapper.pageBaseDiscloseCount(param);
        page.setTotal(aLong);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<String> selectNameList() {
        return baseDiscloseMapper.selectNameList();
    }
}
